package com.ruoyi.web.controller.common;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.Email;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version :
 * @program: easyBuy
 * @description: 邮箱Controller
 * @author: 周爱鸿
 * @create: 2020-09-08 16:06
 **/
@RestController
@RequestMapping("mail")
@Api(description = "邮件发送接口")
public class MailController {
	@Autowired(required = false)
	private JavaMailSender javaMailSender;
	@Autowired
	private RedisCache redisCache;

	@Value("${spring.maill.username:2425123689@qq.com}")
	private String mail;


	@GetMapping("/sendMail")
	@ApiOperation("发送邮件")
	public AjaxResult testSend(String email)  {
		if (StringUtils.isEmpty(email)){
			return AjaxResult.error("邮箱不能为空");
		}
		String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		Pattern p = Pattern.compile(regEx1);
		Matcher m = p.matcher(email);

		if (!m.matches()){
			return AjaxResult.error("邮箱不合法,请重新输入");
		}

		//生成6位验证码
		String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
		redisCache.setCacheObject(email,verifyCode,2, TimeUnit.MINUTES);
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(mail);
		message.setTo(email);
		message.setSubject("易订货");
		message.setText("尊敬的用户，您的验证码为"+verifyCode+",两分钟内有效,请勿泄露给他人");
		javaMailSender.send(message);
		return AjaxResult.success("邮件发送成功");
	}
}
